/*
 * Project_HSBF.fx
 *
 * Created on 26.04.2010, 10:40:38
 */
package trunk.JavaFX179Labs.src.javafx191labs.rtyurin.lab03;

import javafx.scene.CustomNode;
import java.lang.System;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.effect.Lighting;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Button;
import javafx.scene.shape.Rectangle;
import javafx.scene.effect.light.DistantLight;
import javafx.util.Math;
import javafx.scene.text.TextAlignment;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.util.Sequences;
var   i=0;//post_forming-variable
var mainW = 800; //main_form_width
var mainH = 700; //main_form_height
var saveB:Button;
//var mainN=0;
//_____________vcb___vsp___vvp____vlp___acp
var ma_flags=[false,true,false,true,false];
var sim_chosen:Integer[]=[];
//ma_flas - mass aaplication flags
//[0] - visible currentball bar
//[1] - visible start_panel
//[2] - on (loser/victory)_pannel, winner?
//[3] - visible text_pannel
//[4] - active_choose_panel
//[5] - visible win/los_ __deleted
//mainN - current choosen_N
var rand_balls:Integer[]=[]; //random_balls_array
var rand_MAX:Integer=0;
 var nextB:Button;
var chosen:Integer[] = [0,0,0]; //balls_value
var chosenBN=[false,false,false]; //balls_condition
def radioN = ToggleGroup {};

var t_str=0; //count to_string_ variable
//choiceText - radiobutton choses & N values
def choiceText = ["10", "30", "50", "100"];
//var ircle: Circle;
//bonded random functions
/** Returns an integer between low and high, inclusive. */
function RandB(low: Integer, high: Integer): Integer
{
	return (low + (high - low) * Math.random() + 0.5) as Integer;
}
/** Returns an integer between 0 and limit, inclusive. */
function Rand(limit: Integer): Integer
{
  return RandB(0, limit);
}

function defeat_control():Void
{
for (op in chosen)
if (op==rand_MAX)
{
        ma_flags=false;
        chosenBN=false;
        ma_flags[2]=true;
        insert  win_group into stage.scene.content;
break;
} else
{
        ma_flags=false;
        chosenBN=false;
        insert  lost_group into stage.scene.content;
        }
//println("{ma_flags[2]},{chosen[0]}{chosen[1]}{chosen[2]} - {rand_MAX}");


//insert if(ma_flags[2]==true) Winner_pannel{ } else Loser_pannel { } into stage.scene.content
}
//radio_aray_creation_kit
def Ncho = for (text in choiceText)
           {
            RadioButton {
                toggleGroup: radioN
                text: text
                style: "textFill: white; dotFill: blue"
                font : Font {size: 24,
        name:"Comic Sans MS"}

            }//RadioButton
}
var mainN = bind  java.lang.Integer.parseInt(radioN.selectedButton.text);



//class Loser_pannel extends CustomNode {
//currentball_panel_creation_class
 //   override function create(): Node {
       // var stepn: Number = 20;
        var lost_group:Group;
       // var current: Integer = bind rand_balls[0];
        lost_group =Group {
                   // visible:bind ma_flags[5];
                   // layoutX: 20;
                  //  layoutY: mainH / 2;
                    content: [
                    Rectangle {//BG
                    x: mainW/2-mainW/4, y:mainH/2-mainH/4
                    width:mainW/2
                    height: mainH/2
                    fill: Color.BLACK
                    arcHeight:mainH/2
                    arcWidth: 17
                    stroke:Color.DARKRED
                    strokeWidth:15
                    effect:Lighting
                      {diffuseConstant:1.5,
                      light: DistantLight{azimuth:135}
                      surfaceScale:1
                      specularConstant:1}
}//rectangle
ImageView {
        x: mainW/2-mainW/4+20, y:mainH/2-mainH/4+20
	image: Image {

		url: "{__DIR__}you.jpg";

	}
}
Text { //Winner

        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 27, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2, y:mainH/2-mainH/4+30
	wrappingWidth:mainW/2
        content: "You are Looser"
}
Text { //Winner

        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 20, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2, y:mainH/2-mainH/4+20+40
	wrappingWidth:mainW/2-20
    content:bind "Your Variants:\n{chosen[0]}\n{chosen[1]}\n{chosen[2]}\nMax:{rand_MAX}\nMachine Simulation:\n{sim_chosen[0]}\n{sim_chosen[1]}\n{sim_chosen[2]}"
}
Button {
	text: "Попробовать ещё раз?"
        layoutX: mainW/2+20, layoutY:mainH/2+mainH/4-30
	action: function() {
        delete lost_group  from stage.scene.content;
        ma_flags=[false,true,false,true,false];t_str=0;
        delete rand_balls;


	}
}



                            ]
                    }
               //     }
                //    }
//class Winner_pannel extends CustomNode {
//currentball_panel_creation_class
//    override function create(): Node {
        //var stepn: Number = 20;
        //var saveB:Button;
        var win_group:Group;
        //var current: Integer = bind rand_balls[0];
        win_group = Group {
                   //    visible:bind ma_flags[5];
                   // layoutX: 20;
                   // layoutY: mainH / 2;
                    content: [
                    Rectangle {//BG
                    x: mainW/2-mainW/4, y:mainH/2-mainH/4
                    width:mainW/2
                    height: mainH/2
                    fill: Color.BLACK
                    arcHeight:mainH/2
                    arcWidth: 17
                    stroke:Color.DARKRED
                    strokeWidth:15
                    effect:Lighting
                      {diffuseConstant:1.5,
                      light: DistantLight{azimuth:135}
                      surfaceScale:1
                      specularConstant:1}
}//rectangle
ImageView {
        x: mainW/2-mainW/4+20, y:mainH/2-mainH/4+20
	image: Image {

		url: "{__DIR__}win.jpg";

	}
}





Text { //Winner

        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 27, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2-20, y:mainH/2-mainH/4+30
	wrappingWidth:mainW/2-20
        content: "You are Winner"
}
Text { //Winner

        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 20, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2-20, y:mainH/2-mainH/4+20+40
	wrappingWidth:mainW/2-20
       content:bind "Your Variants:\n{chosen[0]}\n{chosen[1]}\n{chosen[2]}\nMax:{rand_MAX}\nMachine Simulation:\n{sim_chosen[0]}\n{sim_chosen[1]}\n{sim_chosen[2]}"
}


Button {
	text: "Попробовать ещё раз?"
        layoutX: mainW/2+20, layoutY:mainH/2+mainH/4-30
	action: function() {
          
         delete win_group from stage.scene.content;
         ma_flags=[false,true,false,true,false];t_str=0; delete rand_balls;
	}
}


]//content
                    }
                   // }
                   // }




class CurrentBall extends CustomNode {
//currentball_panel_creation_class
    override function create(): Node {
        var stepn: Number = 20;
       // var saveB:Button;
       
        var current: Integer = bind rand_balls[0];
        var GRP:Group = Group {
                    visible:bind ma_flags[0];
                    layoutX: 20;
                    layoutY: mainH / 2;
                    effect: Lighting {
                        diffuseConstant: 1.0
                        specularConstant: 1.0
                        specularExponent: 30
                        surfaceScale: 1.5
                    }
                    content: [//current_ball
                        Circle {
                            centerX: 0, centerY: 0
                            radius: 2 * stepn
                            fill: Color.BLACK
                            layoutX: mainW / 4
                            layoutY: -stepn * 6.8
                        }
                        Text {
                            font: Font {size: 24
                                name: "Comic Sans MS"}
                            x: 10, y: 35
                            content: bind current.toString();
                            layoutX: mainW / 4 - stepn * 2
                            layoutY: -stepn * 5.6
                        }
                      nextB =  Button {
                            text: "Пропустить"
                            layoutX: mainW / 4 - stepn * 2
                            layoutY: -stepn * 3.6
                            action: function () {
                               delete rand_balls[0];
                               t_str=sizeof rand_balls;
                               if((t_str==0)or(i>2)){
                                
                            defeat_control();}

                            }//function
                        }//button
                       saveB = Button {
                             text:   "Отложить"
                             layoutX:mainW/4-stepn*1.76
                             layoutY:-stepn*2
                                action: function() {
                               if(i<2){
                                chosen[i]=current;
                               chosenBN[i]=if(chosen[i]==0) false else true;
                                  i++;
                                } else{ 
                               
                                chosen[i]=current;
                                chosenBN[i]=if(chosen[i]==0) false else true;
                                saveB.disable=true;
                                nextB.text= "Проверить";
                                i++;
                                }
                            delete rand_balls[0];
                            t_str=sizeof rand_balls;

                            }//function
                        }//button

                    ]//contento

                }//group
                return GRP;
    }//node_func
}//Currentball
class Text_bar extends CustomNode {

    override function create(): Node {
             return Group {
               var pcount:Text;
               visible:bind ma_flags[3];
               // layoutX:20;
               // layoutY:mainH-140;
                content:[
                    Rectangle { //information_Nselect
                    x: mainW/2-20, y: 0
                    width:mainW/2
                    height: 660
                    fill: Color.BLACK
                    arcHeight:660
                    arcWidth: 17
                    stroke:Color.DARKRED
                    strokeWidth:15
                    effect:Lighting
                      {diffuseConstant:1.5,
                      light: DistantLight{azimuth:135}
                      surfaceScale:1
                      specularConstant:1}
}
 Rectangle {//ball_count
                    x: 0, y: 0
                    width:120
                    height: 70
                    fill: Color.BLACK
                    arcHeight:70
                    arcWidth: 17
                    stroke:Color.DARKRED
                    strokeWidth:15
                    effect:Lighting
                      {diffuseConstant:1.5,
                      light: DistantLight{azimuth:135}
                      surfaceScale:1
                      specularConstant:1}
}

Text { //ball_count

        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 20, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: 40, y: 43
	wrappingWidth:120
        content:bind "{t_str.toString()}/{mainN.toString()}"
}

Text {
	font : Font {size: 24, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2, y: 30
	wrappingWidth:350
        content: "Выберите желаемое колличество шаров:"
}

Text {
	font : Font {size: 16, name:"Comic Sans MS"}
        fill: Color.WHITE;
        x: mainW/2, y: 120
	wrappingWidth:350
        content: "Чтобы выиграть 1.000.000$ игроку нужно найти макисмальное число, помещенное в шарик.Ведущий берет шарики и засовывает их в лоттерейный барабан.\n Шарики перемешиваются и выпадают по одному. Ведущий берет выпавший шарик и называет число, спрятанное в шарике. Игрок может отложить выпавший шарик. \nИгрок может отложить не более трех шариков.Игрок выигрывает только в том случае, если среди отложенных шариков есть максимальное число.\n После того, как ведущий вынет последний шарик из барабана, определяется, выиграл игрок, или проиграл."

}

       Button {//start_button
	text: "Начать"
        disable: bind ma_flags[4]
        layoutX: mainW-120
                            layoutY:75
	action: function() {
        saveB.disable=false;
        nextB.text="Пропустить";
        var new_rand:Integer=0;
        var tempo=0;
        delete rand_balls;
        i=0;
        for (pn in [0..mainN-1])
        {new_rand=Rand(mainN*1000)+1;
         for (pt in [0..sizeof rand_balls])
         if(new_rand==rand_balls[pt]){
         tempo++; break;}
         if(tempo==0) insert new_rand into rand_balls;
        }
        rand_MAX=Sequences.max(rand_balls) as Integer;
        //------------------------------------
        // machine simulation code
        var re_count:Integer=0;
        var re_tesmp:Integer=mainN*500;
        delete sim_chosen;
        for(smp in rand_balls)
        {println("{smp}");
                if((smp>=re_tesmp)and(smp<=mainN*1000))
                {insert smp into sim_chosen;
                re_tesmp=smp;
                re_count++;
                }
               // if(re_count>=2)break;
        }
        //'corse there are no another optimum algorithm in fully
        //randomized system with a limited count of tries
        //if max number lesser than highlimit/2 we cannot find him
        //but with 3 tries we never could find him in sequence bigger than 0
        //------------------------------------
        //println("max={rand_MAX}");
                ma_flags[4]=true;
                ma_flags[0]=true;
                ma_flags[1]=true;
                t_str=sizeof rand_balls;
	}//end_function
}



                   ]
            }}}

class ChosenBalls extends CustomNode {

    override function create(): Node {
        var step:Number =20 ;

           // var mainh = bind;

           
        return Group {
                layoutX:-10;
                //visible:bind ma_flags[1]
                layoutY:mainH-150;
                effect: Lighting {
                diffuseConstant: 1.0
                specularConstant: 1.0
                specularExponent: 30
                surfaceScale: 1.5
            }
            content:[
                   
for(x in [0..2]) {
            println("bla{x}");
              Circle {
	centerX: 3.5*step, centerY: 1.2*step
	radius: 2*step
        id:"bla{x}"

	fill: Color.BLACK
        layoutX:step+6*x*step;
        layoutY:1*step;
        visible: bind chosenBN[x];
}


                                }
                                 for(x in [0..2]) {
                Polygon{ points:[ 1*step,1*step,
                              2*step,2*step,
                              5*step,2*step,
                              6*step,1*step,
                              5.5*step,3*step,
                              1.5*step,3*step,
                              1*step,1*step]
                    var color= Color.CYAN;
                    fill: bind color;
                   layoutX:step+6*x*step;
                   layoutY:30;
                   visible:bind ma_flags[0];
                                }}
for(x in [0..2]) {
               Text {
        textAlignment: TextAlignment.JUSTIFY
	font : Font {size: 20
        name:"Comic Sans MS"}
	x: -5, y: 30
	content: bind chosen[x].toString();
        layoutX:3*step+6*x*step;
        layoutY:4*step;
        visible:bind chosenBN[x];
}
                 }
               ]
        };
    }
}
var chBl=ChosenBalls{ };


def stage:Stage = Stage {
    resizable:false;
    width: mainW
        height: mainH
    title: "Hit teh Sky by Finger"
    scene: Scene {
        stylesheets: "{__DIR__}HSBFstyle.css"

        content:[
                ImageView {
	image: Image {
                backgroundLoading: true
                placeholder: Image {
                   url: "{__DIR__}textbgt.gif"}
		url: "{__DIR__}textbgt.gif"
                width:mainW;
                height:mainH;
	}
}




                 Text_bar { }//text_pannel
                ChosenBalls{ } //chosen_balls_pannel
                 CurrentBall { } //current_balls_pannel
                
        HBox{ spacing: 15
              content: Ncho
              layoutX:mainW/2+30;
              layoutY:70;
              visible:bind ma_flags[3];
              disable:bind ma_flags[4];
              

              }//RadioN
             // if(ma_flags[2]==true) Winner_pannel{ } else Loser_pannel { }

        ]//contento
       } }
